package utils;

import constants.NumberConstants;

import java.math.BigDecimal;
import java.util.Objects;

public class DoubleUtils {

    public static Double dealNull(Double d) {
        return Objects.isNull(d) ? NumberConstants.DOUBLE_ZERO : d;
    }

    public static BigDecimal toBigDecimal(Double d) {
        return new BigDecimal(dealNull(d).toString());
    }

    /**
     * @author chenfoxin
     * @description 四舍五入
     * @param d
     * @param scale
     * @date: 2023/7/29 15:17
     * @return java.lang.Double
     */
    public static Double retainDecimal(Double d, int scale) {
        Double dealB = dealNull(d);
        return new BigDecimal(dealB).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /***
     * 加,四舍五入，保留X位
     * @param scale
     * @param a
     * @return
     */
    public static Double add(int scale, Double... a) {
        BigDecimal bdc = new BigDecimal(NumberConstants.DOUBLE_ZERO);
        for (Double d : a) {
            bdc = bdc.add(toBigDecimal(d));
        }
        return bdc.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
